package com.itheima.controller.backend.order;

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
@Slf4j
public class CollectionDifferenceController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron="0 0 0/1 * * ? ") // 每5秒执行一次
    public void calculateDifference() {
        Set<String> setmealUpload = redisTemplate.opsForSet().members("setmeal_upload");
        Set<String> setmealSave = redisTemplate.opsForSet().members("setmeal_save");

        if (setmealUpload == null) {
            setmealUpload = new HashSet<>();
        }
        if (setmealSave == null) {
            setmealSave = new HashSet<>();
        }

        // 计算差集
        Set<String> difference = new HashSet<>(setmealUpload);
        difference.removeAll(setmealSave);

        if (!difference.isEmpty()){
            //遍历difference集合，删除多余文件
            for (String s : difference) {
                //解析元素s文件名，截取'/'后字符串
                String s1 = s.substring(s.lastIndexOf("/") + 1);
                aliOssUtil.delete(s1);
            }
            log.info("已成功删除OSS垃圾图片: {}", difference);
        }else {
            log.info("未发现需要删除的OSS垃圾图片");
        }

        //清空redis集合
        redisTemplate.delete("setmeal_upload");
        redisTemplate.delete("setmeal_save");
    }
}
